package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.PointsStatisticsVO;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.mq.msg.SignInMessage;
import com.tianji.learning.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author 晚风
 * @since 2023-09-25
 */
@Service
@RequiredArgsConstructor
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    private final StringRedisTemplate redisTemplate;

    /**
     * 新增积分
     * @param msg
     * @param sign
     */
    @Override
    public void addPointRecord(SignInMessage msg, PointsRecordType sign) {
        // 校验
        if (msg.getUserId() == null || msg.getPoints() == null){
            return;
        }
        //1. 查询该类型的积分是否有上限  sign.maxPoints 不等于零
        int maxPoints = sign.getMaxPoints();
        int realPoint = msg.getPoints(); // 变量代表实际可以增加的积分
        if (maxPoints > 0){
            //2. 有上限 查询该类型今日所得的积分，条件 用户id  类型 今天  求和
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime dayStartTime = DateUtils.getDayStartTime(now);
            LocalDateTime dayEndTime = DateUtils.getDayEndTime(now);
            QueryWrapper<PointsRecord> wrapper = new QueryWrapper<>();
            wrapper.select("sum(points) as totalPoints");
            wrapper.eq("user_id",msg.getUserId());
            wrapper.eq("type",sign);
            wrapper.between("create_time",dayStartTime,dayEndTime);
            Map<String, Object> map = this.getMap(wrapper);
            int currentPoints = 0; // 当前用户  该积分类型  已得积分
            if (map != null){
                BigDecimal totalPoints = (BigDecimal) map.get("totalPoints");
                currentPoints = totalPoints.intValue();
            }
            if (currentPoints >= maxPoints){
                // 3.判断是否超过每日上限   进入了表示已经超过
                return;
            }
            // 本次获得了多少分
            if (currentPoints + realPoint > maxPoints){
                realPoint = maxPoints - currentPoints;
            }
        }
        // 4.保存积分
        PointsRecord record = new PointsRecord();
        record.setUserId(msg.getUserId());
        record.setPoints(realPoint); // 分值
        record.setType(sign);
        this.save(record);

        // 5. 累加并保存积分到redis  采用zset
        LocalDate now = LocalDate.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + format;
        redisTemplate.opsForZSet().incrementScore(key,msg.getUserId().toString(),realPoint);
    }

    @Override
    public List<PointsStatisticsVO> queryMyTodayPoints() {
        // 1.获取用户id
        Long userId = UserContext.getUser();
        // 2. 查询积分表points_record 条件：user_id 今日 按type分组  type  sum(points)
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime dayStartTime = DateUtils.getDayStartTime(now);
        LocalDateTime dayEndTime = DateUtils.getDayEndTime(now);

        QueryWrapper<PointsRecord> wrapper = new QueryWrapper<>();
        wrapper.select("tyep","sum(points) as points");
        wrapper.eq("user_id",userId);
        wrapper.between("create_time",dayStartTime,dayEndTime);
        wrapper.groupBy("type");
        List<PointsRecord> list = this.list(wrapper);
        if (CollUtils.isEmpty(list)){
            return CollUtils.emptyList();
        }

        List<PointsStatisticsVO> voList  = new ArrayList<>();
        for (PointsRecord r : list) {
            PointsStatisticsVO vo = new PointsStatisticsVO();
            vo.setPoints(r.getPoints());
            vo.setMaxPoints(r.getType().getMaxPoints()); // 积分类型的上限
            vo.setType(r.getType().getDesc()); // 积分类型的中文
            voList.add(vo);
        }
        // 3. 封装vo返回
        return voList;
    }

}
